//
//  VOLFavoriteViewController.m
//  Volver
//
//  Created by administrator on 14-10-14.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLFavoriteViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "REFrostedViewController.h"
#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"

#import "VOLAppDelegate.h"
#import "VOLFavoriteCell.h"
#import "VOLFavoriteCellModel.h"
#import "VOLHouseAllInfoViewController.h"

@interface VOLFavoriteViewController ()
{
    VOLAppDelegate *del;
    JSONDecoder *jd;
    NSFileManager *manager;
    MBProgressHUD *HUD;
    //用来保存数据源的数组
    NSMutableArray *favoriteHouses;
}

@end

@implementation VOLFavoriteViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //初始化一些对象
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    manager = [NSFileManager defaultManager];
    
    //添加标题
    self.title = @"收藏房屋";
    
    //添加菜单按钮
    addLeftNavigationBarButton();
    
    //将noticeLabel隐藏，当需要显示时再显示出来
    self.noticeLabel.hidden = YES;
    
    //初始化房源数组
    favoriteHouses = [NSMutableArray array];
    
    
    /*
     //初始化UIRefreshControl
     UIRefreshControl *rc = [[UIRefreshControl alloc] init];
     //设置背景色
     rc.backgroundColor = kThemeColor;
     
     rc.tintColor = [UIColor whiteColor];
     //设置下拉以后出现的字
     rc.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
     //添加动作
     [rc addTarget:self action:@selector(fHeaderRereshing) forControlEvents:UIControlEventValueChanged];
     //将创建的refresh对象赋给UITableViewController的refreshControl
     self.refreshControl = rc;
     */
    
    //添加编辑按钮
    UIBarButtonItem *editBtn = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(edit:)];
    [editBtn setTintColor:kThemeColor];
    self.navigationItem.rightBarButtonItem = editBtn;
    //默认失效
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    //开启多行编辑功能
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    
    //添加下拉刷新
    [self setupRefresh];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 每次进入收藏夹时都会调用该方法
-(void)viewWillAppear:(BOOL)animated{
    if (del.isRefresh == 0) {//当不是从菜单栏或者发布成功时跳转过来的不用刷新
        return;
    }
    //将是否刷新再置为0
    del.isRefresh = 0;
    //开始刷新
    [self.tableView headerBeginRefreshing];
    
    
}
#pragma mark - 按钮动作
#pragma mark 菜单栏按钮
-(void)showMenu:(id)sender{
    kActionOfMenuButton;
}
#pragma mark 编辑按钮
-(void)edit:(id)sender{
    BOOL isEditing = !self.tableView.editing;
    if (isEditing) {
        [self.tableView setEditing:isEditing animated:YES];
        self.navigationItem.rightBarButtonItem.title = @"删除";
        //        NSLog(@"执行编辑");
    }else{
        
//        NSLog(@"执行删除");
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        [HUD showAnimated:YES whileExecutingBlock:^{
            [self deleteFavorite];
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
        }];
        
        
        self.navigationItem.rightBarButtonItem.title = @"编辑";
        [self.tableView setEditing:isEditing animated:YES];
    }
}

#pragma mark 删除收藏操作
-(void)deleteFavorite{
    //获取被选中的cell的indexPath，
    NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];
    if (selectedRows.count == 0) {
        return;
    }
    
    //创建数组，将删除成功的indexPath加入其中，删除cell时用到
    NSMutableArray *deletedArray = [NSMutableArray array];
    
    //创建一个堆，将删除成功的indexPath.row加入其中，删除historyData中的数据时用到
    NSMutableIndexSet *deletedSet = [NSMutableIndexSet new];
    
    //遍历数组删除数据
    for (NSIndexPath *indexPath in selectedRows) {
        VOLFavoriteCellModel *model = favoriteHouses[indexPath.row];
        
        //连接网络删除订单表中的内容
        int isDelete = [self deleteFavoriteFormTable:model.houseID];
        
        if (isDelete) {//删除成功
            //将indexPath加入到deletedArray中
            [deletedArray addObject:indexPath];
            //将indexPath.row加入到deletedSet中
            [deletedSet addIndex:indexPath.row];
        }
        
    }
    
    if (deletedArray.count == 0) {
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //遍历结束时删除对应的数据和cell
        //先删除数据
        [favoriteHouses removeObjectsAtIndexes:deletedSet];
        //再删除cell
        [self.tableView deleteRowsAtIndexPaths:deletedArray withRowAnimation:UITableViewRowAnimationAutomatic];
        
        
        //删除完之后如果historyData为空，要将编辑按钮失效
        if (favoriteHouses.count == 0) {
            self.navigationItem.rightBarButtonItem.enabled = NO;
        }
    });
    
    
}

#pragma mark 连网删除收藏表中的内容
-(int)deleteFavoriteFormTable:(int)houseID{
    NSString *urlstr = [NSString stringWithFormat:@"%@favorite/deleteFavorite?userID=%d&houseID=%d",kHTTPHome,del.currentUser.userID,houseID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data) {
        NSDictionary *dic = [jd objectWithData:data];
        int result = [[dic objectForKey:@"status"] intValue];
        return result;
    }else{
        NSLog(@"deleteFavoriteFormTable------data为空");
        return 0;
    }
}

#pragma mark - 设置上拉、下拉
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(fHeaderRereshing)];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    //    [self.tableView addFooterWithTarget:self action:nil];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"拼命加载中...";
    
    self.tableView.footerPullToRefreshText = @"上拉加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载";
    self.tableView.footerRefreshingText = @"拼命加载中...";
}

#pragma mark - 刷新方法
-(void)fHeaderRereshing{
    // 1.添加数据
    NSLog(@"加载数据");
    
    //加载数据，用异步方式
    [self loadFavoriteHouses];
}

#pragma mark - 加载数据
#pragma mark 加载房屋数据
-(void)loadFavoriteHouses{
    //采用异步方式
    
    //发送异步请求
    NSString *urlstr = [NSString stringWithFormat:@"%@favorite/searchAllFavoriteByUserID?userID=%d",kHTTPHome,del.currentUser.userID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    //设置代理
    request.delegate = self;
    [request startAsynchronous];
}


#pragma mark - 代理方法

#pragma mark 异步请求代理方法
#pragma mark 请求完成的方法：
-(void)requestFinished:(ASIHTTPRequest *)request{
    //得到返回数据
    NSData *data = [request responseData];
    
    if (data == nil) {
        NSLog(@"favorite------data为空");
        return;
    }
    
    NSDictionary *dic = [jd objectWithData:data];
    
    //首先判断favoriteHouses是否为空，如果不是，先清空
    if (favoriteHouses.count != 0) {
        [favoriteHouses removeAllObjects];
    }
    
    //得到房屋数组
    NSArray *houseArray = [dic objectForKey:@"favoriteHouses"];
    
    //遍历这个数组，将内容取出
    for (NSDictionary *obj in houseArray) {
        VOLFavoriteCellModel *model = [[VOLFavoriteCellModel alloc] init];
        
        model.favoriteID = [[obj objectForKey:@"favorite_id"] intValue];
        model.houseID = [[obj objectForKey:@"house_id"] intValue];
        model.houseTitle = [obj objectForKey:@"house_title"];
        kGetHouseType(model.houseType, [[obj objectForKey:@"house_type"] intValue]);
        model.housePrice = [[obj objectForKey:@"house_price"] floatValue];
        
        NSString *province = [obj objectForKey:@"house_province"];
        NSString *city = [obj objectForKey:@"house_city"];
        NSString *street = [obj objectForKey:@"house_street"];
        model.houseAddress = [NSString stringWithFormat:@"%@%@%@",province,city,street];
        model.houseOwner = [[obj objectForKey:@"house_owner"] intValue];
        model.houseImageName = [obj objectForKey:@"image_name"];
        model.houseExpirationdate = [[obj objectForKey:@"house_expirationdate"] doubleValue];
        
        //添加到favoriteHouses中
        [favoriteHouses addObject:model];
    }
    
    //遍历完成后，返回主线程更新界面
    //判断是否有收藏的房屋
    if (favoriteHouses.count == 0) {
        //显示提示Label
        self.noticeLabel.text = @"显示您所收藏的房子";
        self.noticeLabel.textColor = kThemeColor;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.noticeLabel.hidden = NO;
    }else{
        //编辑按钮有效
        self.navigationItem.rightBarButtonItem.enabled = YES;
        self.noticeLabel.hidden = YES;
    }
    
    //刷新tableView
    [self.tableView reloadData];
    
    //停止刷新
    [self.tableView headerEndRefreshing];
    
    
}

#pragma mark 请求失败的方法：
-(void)requestFailed:(ASIHTTPRequest *)request{
    //停止刷新动作
    [self.tableView headerEndRefreshing];
    NSLog(@"favorite-----请求失败");
}


#pragma mark - Table view Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return favoriteHouses.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"favoriteCell";
    VOLFavoriteCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    cell.houseTypeAndPriceLabel.textColor = kPriceLabelColor;
    cell.houseAddressLabel.textColor = kPriceLabelColor;
    
    //旋转
    cell.cellNoticeLabel.transform = CGAffineTransformMakeRotation(M_PI_4/2);
    
    VOLFavoriteCellModel *model = favoriteHouses[indexPath.row];
    cell.houseTitleLabel.text = model.houseTitle;
    cell.houseTypeAndPriceLabel.text = [NSString stringWithFormat:@"%@ · ￥%.1f/晚",model.houseType,model.housePrice];
    cell.houseAddressLabel.text = model.houseAddress;
    
    //加载图片
    //先判断是否有这个路径存在，如果没有要先创建
    NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/houseImages/%d",kGetDocumentsPath,del.currentUser.userID,model.houseID];
    if (![manager fileExistsAtPath:imageDocumentPath]) {
        [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //先从本地查找是否已有图片
    NSString *imagePath = [NSString stringWithFormat:@"%@%d/houseImages/%d/%@",kGetDocumentsPath,del.currentUser.userID,model.houseID,model.houseImageName];
    if ([manager fileExistsAtPath:imagePath]) {
        cell.houseImage.image = [UIImage imageWithContentsOfFile:imagePath];
    }
    else{
        [self loadImage:model.houseImageName houseID:model.houseID indexPath:indexPath imagePath:imagePath];
    }
    
    //判断房屋是否过期
    double isDue = model.houseExpirationdate - kGetCurrentTime;
    //将下面这个属性置为NO，这样在旋转的时候大小就不会变了
    cell.cellNoticeLabel.autoresizingMask = NO;
    
    if (isDue < 0) {//过期
        //设置过期提示字体颜色，内容
        cell.cellNoticeLabel.textColor = kThemeColor;
        cell.cellNoticeLabel.text = @"已过期";
        cell.cellNoticeLabel.hidden = NO;
        //过期房屋houseTitleLabel的字体变颜色
        cell.houseTitleLabel.textColor = kPriceLabelColor;
        //houseImageView透明度降为一半
        cell.houseImage.alpha = 0.5;
        
        //设置完毕直接返回 cell
        return cell;
    }else{
        
        //即将过期提示
        if (isDue < kOneDaySeconds * 10) {
            //如果还有3天过期，显示“即将过期”提示
            //设置提示字体颜色，内容
            cell.cellNoticeLabel.textColor = kOrangeColor;
            cell.cellNoticeLabel.text = @"即将过期";
            cell.cellNoticeLabel.hidden = NO;
        }else{
            cell.cellNoticeLabel.hidden = YES;
        }
        
        //没有过期的时候，将houseImageView透明度复原，cellNoticeLable隐藏，将houseTitleLabel的字体颜色恢复
        cell.houseImage.alpha = 1;
        cell.houseTitleLabel.textColor = kBlackColor;
        
    }
    
    
    return cell;
}

#pragma mark 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;
}

#pragma mark 点击某一个cell时
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableView.editing) {
        return;
    }
    
    //取消点击时的背影色
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //获取model
    VOLFavoriteCellModel *model = favoriteHouses[indexPath.row];
    if (model.houseExpirationdate - kGetCurrentTime < 0) {//过期的房屋不能跳转
        return;
    }
    
    //跳转查看所有房屋信息界面
    //点击某个cell时跳转
    VOLHouseAllInfoViewController *houseAllInfo = [self.storyboard instantiateViewControllerWithIdentifier:@"houseAllInfoController"];
    //传递参数
    
    houseAllInfo.sourceFrom = 3;
    houseAllInfo.userID = model.houseOwner;
    houseAllInfo.houseID = model.houseID;
    
    [self.navigationController pushViewController:houseAllInfo animated:YES];
    
}

#pragma mark 加载图片
-(void)loadImage:(NSString *)imageName houseID:(int)houseID indexPath:(NSIndexPath *)indexPath imagePath:(NSString *)imagePath{
    
    //开启新线程加载图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //组装image的url
        NSString *urlstr = [NSString stringWithFormat:@"%@%d/%@",kHouseImageHome,houseID,imageName];
        NSURL *url = [NSURL URLWithString:urlstr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        if (image !=nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                VOLFavoriteCell *cell = (VOLFavoriteCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                cell.houseImage.image = image;
                //本地保存图片
                [data writeToFile:imagePath atomically:YES];
            });
        }
        else{
            NSLog(@"没有图片");
        }
    });
    
}
@end






